本文主要针对Sliding Window类型的算法进行总结归纳解题模板,适用于大部分解决字符串子问题的算法。这里将列举一下比较有代表性的,在每个解题的代码中都标注了一些具体的模版规则。
Sliding Window Template(解题模板)
Sliding Window问题模板代码:
1 | public class Solution { |
P438. Find All Anagrams in a String
问题描述(难度中等)
Given a string s and a non-empty string p, find all the start indices of p‘s anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
Example 1:
1 | Input: |
Example 2:
1 | Input: |
解题代码
利用Sliding Window算法。代码如下,备注部分思路模板。
1 | package P438; |
P76. Minimum Window Substring
####问题描述(难度偏难)
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
Example:
1 | Input: S = "ADOBECODEBANC", T = "ABC" |
Note:
- If there is no such window in S that covers all characters in T, return the empty string
""
. - If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
解题代码
1 | package P76; |
P30. Substring with Concatenation of All Words
问题描述(难度偏难)
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
Example 1:
1 | Input: |
Example 2:
1 | Input: |
解题代码
这道题关键点是words的数组中单词的长度是一致的,实际上演变为sliding window的变型,时间复杂度依旧是O(N)。
1 | package P30; |
P567. Permutation in String
####问题描述(难度中等)
Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string’s permutations is the substring of the second string.
Example 1:
1 | Input: s1 = "ab" s2 = "eidbaooo" |
Example 2:
1 | Input:s1= "ab" s2 = "eidboaoo" |
Note:
- The input strings only contain lower case letters.
- The length of both given strings is in range [1, 10,000].
解题代码
1 | package P567; |
P424. Longest Repeating Character Replacement
####问题描述(难度中等)
Given a string s
that consists of only uppercase English letters, you can perform at most k
operations on that string.
In one operation, you can choose any character of the string and change it to any other uppercase English character.
Find the length of the longest sub-string containing all repeating letters you can get after performing the above operations.
Note:
Both the string’s length and k will not exceed 104.
Example 1:
1 | Input: |
Example 2:
1 | Input: |
解题代码
方法一:HashMap(N^2)
1 | package P424; |
方法二:一遍遍历(N)
方法一中我们每次都要找到当前窗口出现频率最多的key,以此来判断当前窗口是否满足条件,实际上我们不需要每次都去找到当前窗口出现频率最多的key,而只需要记录当前end索引对应的字符加入后最大频率的字母是否改变,改变了就重置最大频率。这样即使我们当前窗口最大频率不是最准确的,但是窗口永远不会大于最大频率+k。
1 | class Solution { |
总结
主要总结下Sliding Window的模板。